package com.hedl.classroom.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hedl.classroom.mapper.XcMenuMapper;
import com.hedl.classroom.mapper.XcUserMapper;
import com.hedl.classroom.model.dto.AuthParamsDto;
import com.hedl.classroom.model.dto.XcUserExt;
import com.hedl.classroom.model.po.XcMenu;
import com.hedl.classroom.model.po.XcUser;
import com.hedl.classroom.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Big Watermelon
 * @description
 * @date 2023/12/08/18:35
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {

    @Resource
    private XcUserMapper xcUserMapper;

    @Resource
    private XcMenuMapper xcMenuMapper;

    @Resource
    private ApplicationContext applicationContext;

    /**
     * @param username 根据username账号查询数据库
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //传入的请求认证的参数就是AuthParamsDto
        AuthParamsDto authParamsDto = null;
        try{
            authParamsDto = JSON.parseObject(username, AuthParamsDto.class);
        }catch (Exception e){
            throw new RuntimeException("请求认证的参数不符合要求！");
        }

        //认证累心，有password，wv...
        String authType = authParamsDto.getAuthType();
        //根据认证类型从spring容器中，取出指定的bean，这里就是另一种注入的方式
        String beanName = authType+"_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        //调用统一execute方法完成认证
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        //封装xcUserExt用户信息为UserDetails,密码是Spring Security给我们做比对的
        //根据UserDetails对象生成令牌
        UserDetails userDetails = getUserPrincipal(xcUserExt);
        return userDetails;
    }

    /**
     * 查询用户信息
     * @param xcUserExt 用户id，主键
     * @return 用户信息
     */
    public UserDetails getUserPrincipal(XcUserExt xcUserExt){
        //获取密码
        String password = xcUserExt.getPassword();
        //权限
        String[] authorities = {"test"};

        //根据用户id查询用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUserExt.getId());
        if (xcMenus.size()>0){
            List<String> permissions = new ArrayList<>();
            xcMenus.forEach(
                    m->{
                        //拿到了用户拥有的权限标识符
                        permissions.add(m.getCode());
                    }
            );
            //将permissions转成数组
            authorities = permissions.toArray(new String[0]);
        }



        /**
         * 这里我们扩展用户身份信息，在jwt令牌中存储用户的昵称、头像、qq等信息；
         * 方法一：就是自定义扩展UserDetails
         * 方法二：就是如下操作，把得到的对象转为json结构的数据，注意把密码先排除了，不然会暴露的
         */
        xcUserExt.setPassword(null);
        String UserJson = JSON.toJSONString(xcUserExt);
        UserDetails userDetails = User.withUsername(UserJson).password(password).authorities(authorities).build();

        return userDetails;
    }
}
